<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.key" placeholder="部门名称/部门主管"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryData">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="角色名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="角色唯一标识" width="150" sortable>
      </el-table-column>
      <el-table-column label="操作" width="350">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handleRole(scope.$index, scope.row)">授权</el-button>
          <el-button type="primary" size="small" @click="handleMenu(scope.$index, scope.row)">菜单</el-button>

        </template>
      </el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
          el-pagination 表示分页
          @size-change : 每页条数改变的时候会触发的方法
          @current-change: 当页数改变的时候
          :current-page: 绑定当前页数据
          :page-sizes="[100, 200, 300, 400]" : 每页多少条的选择
          :page-size="100" 每页的条数
          :total="400" 总条数
          layout="total, sizes, prev, pager, next, jumper"
     -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="search.currentPage"
          :page-sizes="[10, 20]"
          :page-size="100"
          style="float: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>

		</el-col>

    <!--菜单界面-->
    <el-dialog title="菜单" :visible.sync="menuFormVisible" :close-on-click-modal="false">
      <el-form :model="menuForm" label-width="80px" ref="addForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="menuForm.role.name" disabled auto-complete="off"></el-input>
        </el-form-item>
        <!--
         :props="props" 定义前端显示的数据 与 对象 属性是匹配的
         :data="data" 绑定数据源，也就是查出来的权限树
         default-expand-all 默认展开
         ref="tree" 给树形控件取一个名字
       -->
        <el-form-item label="菜单" prop="name">
          <el-tree
              :props="props"
              :data="menuData"
              default-expand-all
              node-key="id"
              ref="tree"
              show-checkbox
          >
          </el-tree>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="menuFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="roleMenu" >提交</el-button>
      </div>
    </el-dialog>

    <!--授权界面-->
    <el-dialog title="授权" :visible.sync="roleFormVisible" :close-on-click-modal="false">
      <el-form :model="roleForm" label-width="80px" ref="addForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.role.name" disabled auto-complete="off"></el-input>
        </el-form-item>
        <!--
         :props="props" 定义前端显示的数据 与 对象 属性是匹配的
         :data="data" 绑定数据源，也就是查出来的权限树
         default-expand-all 默认展开
         ref="tree" 给树形控件取一个名字
       -->
        <el-form-item label="权限" prop="name">
          <el-tree
              :props="props"
              :data="data"
              default-expand-all
              node-key="id"
              ref="tree"
              show-checkbox
          >
          </el-tree>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="roleAuth" >提交</el-button>
      </div>
    </el-dialog>



		<!--新增和修改界面-->
		<el-dialog title="新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" ref="addForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="唯一标识" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" >提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

	export default {
		data() {
			return {

			  menuData:[],
        data:[],

        props: {
          label: 'name',
          children: 'children'
        },

        menuFormVisible:false, //菜单弹框默认关闭
        roleFormVisible:false, //授权弹框默认关闭

        roleForm:{
          role:{id:null,name:""},
          permissionList:[]
        },

        menuForm:{
          role:{id:null,name:""},
          menuList:[]
        },

        search: {
          key: '',
          pageSize:10,
          currentPage:1
        },

        pageInfo:{
          data: [],
          total: 0,
        },

				listLoading: false,
				sels: [],//列表选中列

       saveFormVisible:false,
        saveForm:{
          id:null,
          name:"",
          sn:""
        }

			}
		},
		methods: {

      //点击菜单按钮
      handleMenu(index,row){
        this.menuFormVisible=true;
        this.menuForm.role = row;
        this.getMenus()
      },

      //查询菜单
      getMenus(){
        //发送请求
        this.$http.get("/menu/tree")
            .then(res =>{
              res = res.data
              if(res.success){
                console.log(res.data)
                this.menuData = res.data;
                // 回显 权限树数据
                this.queryMenuByRoleId();
              }
            })
            .catch(res =>{})
      },


      //菜单弹框的提交按钮
      roleMenu(){
        //通过node 方式，获取选中的菜单树节点，把数据传给roleForm
        this.menuForm.menuList = this.$refs.tree.getCheckedNodes();
        // console.log(this.$refs.tree.getCheckedKeys());
        // 发送请求
        this.$http.post("/role/roleMenu",this.menuForm)
            .then(res=>{
              res=res.data
              if(res.success){
                this.$message({type:"success",message:"设置菜单成功"});
                this.menuFormVisible = false;
              }
            })
            .catch(res=>{})
      },

      // 根据角色的id 查询 角色所对应的菜单
      queryMenuByRoleId(){
        this.$http.post("/role/roleMenu/"+this.menuForm.role.id)
            .then(res=>{
              res=res.data
              if(res.success){
                var ids = res.data;
                //ids 为通过角色id查出的全部权限id
                this.$refs.tree.setCheckedKeys(ids); //回显的主要代码
              }
            })
            .catch(res=>{})
      },


      // 根据角色的id 查询 角色所对应的权限
      queryAuthByRoleId(){
        this.$http.post("/role/roleAuth/"+this.roleForm.role.id)
            .then(res=>{
              res=res.data
              if(res.success){
                var ids = res.data;
                //ids 为通过角色id查出的全部权限id
                this.$refs.tree.setCheckedKeys(ids); //回显的主要代码
              }
            })
            .catch(res=>{})
      },

		  //授权弹框的提交按钮
      roleAuth(){
        //通过node 方式，获取选中的权限树节点，把数据传给roleForm
        this.roleForm.permissionList = this.$refs.tree.getCheckedNodes();
        // console.log(this.$refs.tree.getCheckedKeys());
        // 发送请求
        this.$http.post("/role/roleAuth",this.roleForm)
            .then(res=>{
              res=res.data
              if(res.success){
                this.$message({type:"success",message:"授权成功"});
                this.roleFormVisible = false;
              }
            })
            .catch(res=>{})
      },


      /**
       *  回显和 设置都有2中方案 一种是通过 node  一种是通过 key  如果通过key 不管是设置还是获取都要有 node-key属性
       *  node的回显有点麻烦
       *  需要查询 该角色所有的 权限信息
       *  但是如果通过key 回显会简单一点 只需要 权限的id
       */
       //查询权限树
       getTree(){
         //发送请求
         this.$http.get("/permission/tree")
             .then(res =>{
               res = res.data
               if(res.success){
                 console.log(res.data)
                 this.data = res.data;
                 // 回显 权限树数据
                 this.queryAuthByRoleId();
               }
             })
             .catch(res =>{})
       },

		  //点击授权按钮
      handleRole(index,row){
      this.roleFormVisible=true;
      this.roleForm.role = row;
      this.getTree()
    },

		  //获取部门树
      getDeptTree(){
        //发送请求
        this.$http.get("/role/deptTree")
            .then(res =>{
              res = res.data
              if(res.success){
                this.deptTree = res.data;
              }
            })
            .catch(res =>{})
      },

		  //获取部门主管 数组
      getManagers(){
        //发送请求
        this.$http.get("/employee")
        .then(res =>{
           res = res.data
           if(res.success){
             this.employees = res.data;
           }
        })
        .catch(res =>{})
      },

      // 点击新增
      handleAdd(){
        this.saveFormVisible = true; //显示弹出框
        this.saveForm= {
          id:null,
          name:"",
          sn:""
        }

      },

      // 点击查询的方法
      queryData(){
        this.search.currentPage = 1
        this.getRoles()
      },

      // 每页条数变动的时候
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.search.pageSize = val
        this.getRoles()
      },

			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
        // val 指的是当前的页数
        this.search.currentPage = val;
        this.getRoles();
			},

      //获取角色列表
      getRoles() {
        this.listLoading=true;
        this.$http.post("/role",this.search)
            .then(res=>{
              this.listLoading=false;
              res = res.data;
              console.log(res)
              if(res.success){
                // this.roles = res.data.data
                // this.total = res.data.total
                this.pageInfo = res.data; //将查出的数据总数和数据赋给pageInfo，进而给列表传数据并显示
              }
            })
            .catch(res=>{})
        // this.listLoading = true;

      },

			//删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {  //点击确认
          this.listLoading = true;
          this.$http.delete("/role/"+row.id)  //发送删除请求，并传id
              .then(res=>{
                res = res.data
                this.listLoading = false;  //加载框消失
                if(res.success){
                  this.$message({type:"success",message:"删除成功"});
                }else{
                  this.$message.error("删除失败"+res.msg)
                }
                this.search.currentPage= 1; //删完回到第一页
                this.getRoles();  //重新查询
              })
              .catch(res=>{})

        }).catch(() => {

        });
      },



			//显示新增和修改界面
			handleSave: function (index,row) {
        console.log(row)
				this.saveFormVisible = true;
				this.saveForm = JSON.parse(JSON.stringify(row)); //数据回显,深拷贝

			},


			//新增和修改的提交按钮
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {

							//NProgress.start();
							let para = Object.assign({}, this.saveForm); //获取输入框的值

							//发送请求
              this.$http.put("/role",para)
              .then(res =>{
                this.saveFormVisible = false; //关闭弹出框
                this.$message({type:"success",message:"保存成功"});
                this.getRoles() //重新查询
              })
              .catch(res =>{

              })

						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},

			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => { //点击确认
					this.listLoading = true;
          //发送请求
          this.$http.patch("/role",ids)  //发送删除请求，并传id
              .then(res=>{
                res = res.data
                this.listLoading = false;  //加载框消失
                if(res.success){
                  this.$message({type:"success",message:"删除成功"});
                }else{
                  this.$message.error("删除失败"+res.msg)
                }
                this.search.currentPage= 1; //删完回到第一页
                this.getRoles();  //重新查询
              })
              .catch(res=>{})

				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getRoles();
		}
	}

</script>

<style scoped>

</style>